﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;


namespace Infrastructure.Security
{
    public static class AesHelper
    {

        public static string AESEncrypt(string data, string key, string vector)
        {
          
            byte[] inArray = AESEncrypt(Encoding.UTF8.GetBytes(data), key, vector);
            if (inArray == null)
                return (string)null;
            return Convert.ToBase64String(inArray);
        }

        public static byte[] AESEncrypt(byte[] data, string key, string vector)
        {


            //Check.Argument.IsNotEmpty<byte>((ICollection<byte>)data, nameof(data));
            //Check.Argument.IsNotEmpty(key, nameof(key));
            //Check.Argument.IsNotOutOfRange(key.Length, 32, 32, nameof(key));
            //Check.Argument.IsNotEmpty(vector, nameof(vector));
            //Check.Argument.IsNotOutOfRange(vector.Length, 16, 16, nameof(vector));
            byte[] buffer = data;
            byte[] rgbKey = new byte[32];
            Array.Copy((Array)Encoding.UTF8.GetBytes(key.PadRight(rgbKey.Length)), (Array)rgbKey, rgbKey.Length);
            byte[] rgbIV = new byte[16];
            Array.Copy((Array)Encoding.UTF8.GetBytes(vector.PadRight(rgbIV.Length)), (Array)rgbIV, rgbIV.Length);
            byte[] numArray = (byte[])null;
            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                try
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, aes.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(buffer, 0, buffer.Length);
                            cryptoStream.FlushFinalBlock();
                            numArray = memoryStream.ToArray();
                        }
                    }
                }
                catch
                {
                    numArray = (byte[])null;
                }
                return numArray;
            }
        }

    }
}
